var err_msg	= '<div class="alert alert-warning alert-dismissible fade in" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>Error : &nbsp;</strong>{err}</div>';
var err_reg	= new RegExp('({err})', 'g');
var ws		= new WebSocket('ws://' + location.host + '/ws');
var ws_tail	= null; 

$('#mdl-edit').on('show.bs.modal', function(e) {
	var btn		= $(e.relatedTarget);
	var name	= btn.data('watcher-name');
	var cmd		= btn.data('watcher-cmd');
	var dir		= btn.data('watcher-dir');
	var retries	= btn.data('watcher-retries');

	$(this).find('#in-org-name').val(name);
	$(this).find('#in-name').val(name);
	$(this).find('#in-cmd').val(cmd);
	$(this).find('#in-dir').val(dir);
	$(this).find('#in-retry').val(retries);
});

$('#mdl-tail').on('show.bs.modal', function(e) {
	var btn		= $(e.relatedTarget);
	var name	= btn.data('watcher-name');

	if (ws_tail != null) {
		ws_tail.close();
		ws_tail = null;
	}

	ws_tail = new WebSocket('ws://' + location.host + '/tail/' + name);
	ws_tail.onmessage = function(evt) {
		try {
			var data = JSON.parse(evt.data);
			var dom = $('#mdl-tail pre').get(0);

			if (dom != null) {
				if (data.action == 'tail_sync') {
					dom.innerHTML = data.data;
				} else {
					dom.innerHTML = dom.innerHTML + data.data;
				}
			}			
		} catch (err) {
		}		
	}
});

$('#mdl-tail').on('hide.bs.modal', function() {
	if (ws_tail != null) {
		ws_tail.close();
		ws_tail = null;
	}
});

function status2label(status) {
	if (status == 0) {
		return '<span class="label label-default">STOPPED</span>';
	} else if (status == 1) {
		return '<span class="label label-success">RUNNING</span>';
	} else if (status == 2) {
		return '<span class="label label-danger">FATAL</span>';
	} else {
		return '<span class="label label-warning">RETRY</span>';
	}
}

function watcher2html(watcher) {
	return '<td>' + watcher.name + '</td>'
		+ '<td class="status">' + status2label(watcher.status) + '</td>'
		+ '<td class="cpu">' + 0 + '</td>'
		+ '<td class="vert">' + 0 + '</td>'
		+ '<td class="res">' + 0 + '</td>'
		+ '<td>'
		+ '<button onclick="start_watcher(\'' + watcher.name + '\')" class="btn btn-default btn-xs start" ' + (watcher.status == 1 ? 'disabled' : '') + '><span class="glyphicon glyphicon-play" aria-hidden="true"></span> Start</button>&nbsp;'
		+ '<button onclick="stop_watcher(\'' + watcher.name + '\')" class="btn btn-default btn-xs stop" ' + (watcher.status != 1 ? 'disabled' : '') + '><span class="glyphicon glyphicon-stop" aria-hidden="true"></span> Stop</button>&nbsp;'
		+ '<button class="btn btn-default btn-xs" data-toggle="modal" data-target="#mdl-tail" data-watcher-name="'+ watcher.name + '"><span class="glyphicon glyphicon-list-alt" aria-hidden="true"></span> Tail</button>&nbsp;'
		+ '<button class="btn btn-info btn-xs" data-toggle="modal" data-target="#mdl-edit" data-watcher-name="'+ watcher.name + '" data-watcher-cmd="' + watcher.cmd + '" data-watcher-dir="' + watcher.dir + '" data-watcher-retries="' + watcher.retry + '"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span> Edit</button>&nbsp;'
		+ '<button onclick="delete_watcher(\'' + watcher.name + '\')" class="btn btn-danger btn-xs delete" ' + (watcher.status == 1 ? 'disabled' : '') + '><span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete</button>'
		+ '</td>';
}

function reload() {
	$.get('/api/reload', function(ret) {
	}, 'json');
}

function add_watcher() {
	$('#form-add').ajaxSubmit({
		dataType: 'json',
		success: function(ret) {
			if (ret.err != null) {
				var dom = $('#mdl-add #err').get(0);
				dom.innerHTML = err_msg.replace(err_reg, ret.err);
			} else {
				$('#mdl-add').modal('hide');
			}
		}
	});
}

function edit_watcher() {
	$('#form-edit').ajaxSubmit({
		dataType: 'json',
		success: function(ret) {
			if (ret.err != null) {
				var dom = $('#mdl-edit #err').get(0);
				dom.innerHTML = err_msg.replace(err_reg, ret.err);
			} else {
				$('#mdl-edit').modal('hide');
			}
		}
	});
}

function start_watcher(name) {
	$.get('/api/start?name=' + name, function(ret) {
	}, 'json');
}

function stop_watcher(name) {
	$.get('/api/stop?name=' + name, function(ret) {
	}, 'json');
}

function delete_watcher(name) {
	$.get('/api/delete?name=' + name, function(ret) {
	}, 'json');
}

ws.onclose = function(evt) {
	$('#conn-err').get(0).innerHTML = err_msg.replace(err_reg, 'Connection lost with supervisor!!!');
}

ws.onmessage = function(evt) {
	try {
		var data = JSON.parse(evt.data);
		if (data.action == 'add') {
			var obj		= document.getElementById('watcher-' + (data.rename == null ? data.watcher.name : data.rename));
			var html	= watcher2html(data.watcher);

			if (obj == null) {
				var all = $('#table-watchers');
				var add = $('<tr id="watcher-' + data.watcher.name + '">' + html + '</tr>');
				all.append(add);
			} else {
				if (name != data.watcher.name) $(obj).prop('id', 'watcher-' + data.watcher.name);
				$(obj).html(html);
			}
		} else if (data.action == 'delete') {
			var dom = document.getElementById('watcher-' + data.watcher);
			if (dom != null) dom.remove();
		} else if (data.action == 'status_change') {
			$('#watcher-' + data.watcher + ' .status').html(status2label(data.status));
			$('#watcher-' + data.watcher + ' .start').attr('disabled', data.status == 1);
			$('#watcher-' + data.watcher + ' .stop').attr('disabled', data.status != 1);
			$('#watcher-' + data.watcher + ' .delete').attr('disabled', data.status == 1);
			$('#watcher-' + data.watcher + ' .cpu').html('0');
			$('#watcher-' + data.watcher + ' .vert').html('0');
			$('#watcher-' + data.watcher + ' .res').html('0');
		} else if (data.action == 'update') {
			$.each(data.watchers, function(n, info) {
				$('#watcher-' + info.name + ' .cpu').html(info.cpu);
				$('#watcher-' + info.name + ' .vert').html(info.vert);
				$('#watcher-' + info.name + ' .res').html(info.res);
			});			
		}
	} catch (err) {
		console.log('Unknown message', evt.data, err);
	}	
}

ws.onerror = function(evt) {
	console.log('[WebSocket][E]', evt.data);
}

